package com.wushi.lenovo.asia5b.app_ui.h5;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.ContentLoadingProgressBar;
import android.webkit.WebView;
import android.widget.LinearLayout;

import com.mvp.base.model.ResultModel;
import com.mvp.helper.WCallBack;
import com.mvp.utils.ToastUtil;
import com.wushi.lenovo.asia5b.R;
import com.wushi.lenovo.asia5b.app_config.UserRepository;
import com.wushi.lenovo.asia5b.app_event.AddShopCarEvent;
import com.wushi.lenovo.asia5b.app_model.good.AddCartModel;
import com.wushi.lenovo.asia5b.app_model.h5.H5Bean;
import com.wushi.lenovo.asia5b.app_model.h5.H5GoodBean;
import com.wushi.lenovo.asia5b.app_ui.good.activity.OrderCheckPiActivity;
import com.wushi.lenovo.asia5b.app_ui.other.OrderPackBeforeNoticeDialog;
import com.wushi.lenovo.asia5b.app_ui.other.dialog.ShopCarNoticeDialog;
import com.wushi.lenovo.asia5b.app_ui.shopcar.activity.ShopCarActivity;
import com.wushi.lenovo.asia5b.app_utils.AndroidBug5497Workaround;
import com.wushi.lenovo.asia5b.app_utils.helper.H5Hepler;

import org.greenrobot.eventbus.EventBus;

import java.io.Serializable;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

import static timber.log.Timber.d;

/**
 * ================================================
 * Created by ${chenyuexueer}
 * 时间： 2018/9/18.
 * 说明：商品详情页面
 * ================================================
 */
public class GoodsDetailsActivity extends H5Activity {

    @BindView(R.id.webview_layout)
    LinearLayout webview_layout;
    @BindView(R.id.progress)
    ContentLoadingProgressBar progress;
    @BindView(R.id.web_gooddetail)
    WebView webView;
    protected String url;


    public static void startGoodsDetailsActivity(Context context, int productId) {
        String url = H5Hepler.getH5_Url(String.format("goods?id=%d", productId));
        startGoodsDetailsActivity(context, url);
    }

    public static void startGoodsDetailsActivity(Context context, String url) {
        url = H5Hepler.addAsiaH5Params(url);
        Intent intent = new Intent(context, GoodsDetailsActivity.class);
        intent.putExtra(H5_URL, url);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
//        setStatusTrans();
        return R.layout.activity_goodsdetail;
    }

    @Override
    protected void setContentViewAfter() {
        AndroidBug5497Workaround.assistActivity(this);
    }

    @Override
    protected WebView getWebView() {
        return webView;
    }

    private String productId;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getIntent().hasExtra(H5_URL)) {//商品
            url = getIntent().getStringExtra(H5_URL);
        }
        try {
            if (UserRepository.isLogin()) {
                //查询该商品是否被收藏过
                Uri uri = Uri.parse(url);
                productId = uri.getQueryParameter("id");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        initView();
        initEvent();
        initData();
    }


    @Override
    protected void initView() {
//        showLoadingBar("");
        //使用new方式这是为了解决当(settings.setJavaScriptEnabled(true))之后会出现TextToSpeech的内存泄漏
//        webView = new ScorllWebView(this);
//        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
//        webView.setLayoutParams(layoutParams);
//        webview_layout.addView(webView);
        setting(webView);
        setWebViewChormeClient(webView, progress);

        //防止加载框一直loading
        Disposable subscribe = Observable.timer(15, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(aLong -> {
                    dismissLoadingBar("");
                }, throwable -> {
                    throwable.printStackTrace();
                });
        composite.add(subscribe);
    }


    @Override
    protected void initData() {
        d("--->>>>>>>>---url:" + url);
        webView.loadUrl(url);

//        if (!TextUtils.isEmpty(productId)) {
//            getPresenter().isWished(productId);
//        }
    }

    @Override
    protected void callBackByJs(H5Bean h5Bean1) {
        super.callBackByJs(h5Bean1);
        if (h5Bean1 == null) {
            return;
        }

        if (h5Bean1 instanceof H5GoodBean) {
            H5GoodBean h5GoodBean = (H5GoodBean) h5Bean1;
            d("--->>>>>>>>---开始添加购物车");
            if (UserRepository.isLogin(mActivity)) {
                getPresenter().addGoodMall(h5GoodBean, url);
            }
        }
    }

    @Override
    protected void onPageFinished(String url) {
        super.onPageFinished(url);
//        setWishIcon(productId);
    }

    protected void initEvent() {
        webView.addJavascriptInterface(jsCall, H5_JSCALL_NAME);
    }

    @Override
    public void addGoodMallResult2(ResultModel resultModel) {
        if (resultModel.isSuccess()) {
            ToastUtil.showToast(resultModel.getMsg());
            EventBus.getDefault().post(new AddShopCarEvent());
        }
    }

    @Override
    public void addGoodMallResult(ResultModel<AddCartModel> resultModel, boolean isBuyNow) {
        if (resultModel.isSuccess()) {
            if (resultModel.getData() != null) {
                AddCartModel addCartModel = resultModel.getData();
                if (isBuyNow) {
                    if (addCartModel.getSelectIds() != null) {
                        Intent intent = new Intent(mActivity, OrderCheckPiActivity.class);
                        intent.putExtra("datas", (Serializable) addCartModel.getSelectIds());
                        intent.putExtra("isDaigouGoods", addCartModel.isDaigou());
                        startActivity(intent);
                    }
                } else {
                    if (addCartModel.hasDialog()) {
                        OrderPackBeforeNoticeDialog orderPackBeforeNoticeDialog = new OrderPackBeforeNoticeDialog(mActivity);
                        orderPackBeforeNoticeDialog.title = addCartModel.getTitle();
                        orderPackBeforeNoticeDialog.content = addCartModel.getContent();
                        orderPackBeforeNoticeDialog.contentHtml = true;
                        orderPackBeforeNoticeDialog.ok = addCartModel.getOk();
                        orderPackBeforeNoticeDialog.cancel = addCartModel.getCancel();
                        orderPackBeforeNoticeDialog.show();
                        orderPackBeforeNoticeDialog.setCallBack(new WCallBack<Boolean>() {
                            @Override
                            public void callback(Boolean aBoolean) {
                                if (!aBoolean) {//去购物车
                                    startActivity(new Intent(mActivity, ShopCarActivity.class));
                                } else {//继续购买

                                }
                            }
                        });
                    }
                }
            }
            EventBus.getDefault().post(new AddShopCarEvent());
        } else {
            ShopCarNoticeDialog noticeDialog = new ShopCarNoticeDialog(mActivity,
                    resultModel.getMsg(),
                    "");
            noticeDialog.show();
        }
    }

}
